package ee.pri.pink.kallur.gl.objects;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

public class GLCube implements GLObject {
	
	private final static int NR_OF_VERTICES = 8;
	
	private ShortBuffer faceBuffer;
	 
	private FloatBuffer vertexBuffer;
	
	private FloatBuffer colorBuffer;
	
	private float[] coords = {
		0.0f, 0.0f, 0.0f,
		1.0f, 0.0f, 0.0f,
		1.0f, 1.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
		0.0f, 0.0f, 1.0f,
		1.0f, 0.0f, 1.0f,
		1.0f, 1.0f, 1.0f,
		0.0f, 1.0f, 1.0f
	};
	
	private float[] colors = {
		0.75f, 0.75f, 0.75f, 1.0f,
		0.75f, 0.75f, 0.75f, 1.0f,
		0.75f, 0.75f, 0.75f, 1.0f,
		0.75f, 0.75f, 0.75f, 1.0f,
		0.55f, 0.55f, 0.55f, 1.0f,
		0.55f, 0.55f, 0.55f, 1.0f,
		0.55f, 0.55f, 0.55f, 1.0f,
		0.55f, 0.55f, 0.55f, 1.0f
	};
	
	private short[] faces = {
		0, 1, 2,
		0, 2, 3,
		4, 0, 3,
		4, 3, 7,
		4, 7, 6,
		4, 6, 5,
		5, 6, 2,
		5, 2, 1,
		7, 3, 2,
		7, 2, 6,
		1, 0, 4,
		1, 4, 5
	};

	
	public GLCube() {
		ByteBuffer vbb = ByteBuffer.allocateDirect(NR_OF_VERTICES * 3 * 4);
		vbb.order(ByteOrder.nativeOrder());
		vertexBuffer = vbb.asFloatBuffer();
		
		ByteBuffer cbb = ByteBuffer.allocateDirect(NR_OF_VERTICES * 4 * 4);
		cbb.order(ByteOrder.nativeOrder());
		colorBuffer = cbb.asFloatBuffer();
		
		ByteBuffer ibb = ByteBuffer.allocateDirect(faces.length * 2);
 
	    // short has 2 bytes
	    ibb.order(ByteOrder.nativeOrder());
	    faceBuffer = ibb.asShortBuffer();
	    
	    vertexBuffer.put(coords);
	    faceBuffer.put(faces);
	    colorBuffer.put(colors);
	 
	    vertexBuffer.position(0);
	    faceBuffer.position(0);
	    colorBuffer.position(0);
	}
 

	@Override
	public void render(GL10 gl) {

		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
		gl.glColor4f(0.5f, 0f, 0f, 0.5f);
		 
	    // define the vertices we want to draw
	    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
	    
	    gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);
	 
	    // finally draw the vertices
	    gl.glDrawElements(GL10.GL_TRIANGLES, faces.length, GL10.GL_UNSIGNED_SHORT, faceBuffer);
	    
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
	}

}
